<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="">
    <title>持仓信息反馈</title>
    <!-- 360浏览器急速模式 -->
    <meta name="renderer" content="webkit">
    <!-- 避免IE使用兼容模式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link href="/static/css/bootstrap5.min.css" rel="stylesheet"/>
    <style>

        #userInfo {
            display: flex;
            align-items: center;
        }

        #user-info span {
            margin-right: 10px;
            font-size: 1rem;
            color: #333;
            white-space: nowrap; /* 防止文本换行 */
        }

        #logoutButton:hover {
            text-decoration: underline;
        }

        /* 添加到你的CSS文件中 */
        .holding-info {
            display: flex;
            flex-direction: column;
            padding: 15px;
            margin: 20px 0;
            background-color: #f9f9f9;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .holding-info span {
            font-weight: bold;
            color: #007bff;
        }


        /* 将复选框改为单列布局 */
        .checkbox-grid {
            display: block;
        }

        .checkbox-grid label {
            display: block;
            margin-bottom: 10px; /* 每个复选框之间的间距 */
        }


        /* 必填星号样式 */
        .required::after {
            content: " *";
            color: red;
            font-weight: bold;
        }

        /* 隐藏行业复选框 */
        #industryField {
            display: none;
        }

        /* 让 .holding-info 使用 flex 布局，将内容水平对齐 */
        .holding-info {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px; /* 控制标题和百分比之间的间距 */
        }

        .holding-percentage {
            font-size: 18px;
            color: #da1717;
        }
    </style>
</head>

<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="/templates/client/average-holding-percentage.html">首页</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" aria-current="page" href="/templates/client/news.html">每日资讯</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" aria-current="page" href="/templates/client/chat.html">AI问题解答</a>
                </li>
                <li class="nav-item" shiro:notAuthenticated>
                    <a class="nav-link" href="/templates/client/login.html">登录</a>
                </li>
                <li class="nav-item" shiro:notAuthenticated>
                    <a class="nav-link" href="/templates/client/register.html">注册</a>
                </li>
            </ul>
            <div id="userInfo" class="ms-auto">
                <span class="nav-link">用户昵称</span>
                <button class="nav-link btn btn-link" id="logoutButton">退出登录</button>
            </div>
        </div>

    </div>
</nav>

<div class="container p-5 my-5">
    <h2 class="text-center">欢迎来到杨无敌股友空间</h2>
</div>

<div class="container-md border-top p-5">
    <!-- 添加一个 div 包裹今天的平均持仓和百分比 -->
    <div class="holding-info">
        <h5>今日的平均持仓: <p><span th:text="${averageHoldingPercentage} + '%'"></span></p></h5>
    </div>
    <div class="holding-info">
        <h5>今日的填写人数: <p><span th:text="${submitCount}"></span></p></h5>
    </div>
</div>

<div class="container-md border-top p-5">
    <h2 class="text-center">今日的行业持仓占比</h2>
    <table class="table table-striped">
        <thead>
        <tr>
            <th>行业</th>
            <th>比例 (%)</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="sectorPosition : ${sectorPositions}">
            <td th:text="${sectorPosition.sectorName}"></td>
            <td class="holding-percentage" th:text="${sectorPosition.positionRatio}"></td>
        </tr>
        </tbody>
    </table>
</div>

<div class="container-md border-top p-5">
    <div class="row justify-content-center">
        <h2 class="text-center">您今日的持仓信息</h2>
        <div class="col-md-6">
            <div class="card">
                <div th:if="${userHolding != null}" class="card-header">
                    <h5>持仓比例：<span th:text="${userHolding.holdingPercentage} + '%'"></span></h5>
                    <h5>行业选择：<span th:text="${userHolding.industrySummaryNames}"></span></h5>
                    <p style="color: #9b9b9b">您可以在下方修改您的持仓信息</p>
                </div>
                <div class="card-body">
                    <form id="holdingForm" method="post">
                        <div class="mb-3">
                            <div th:if="${userHolding == null}">
                                <label class="form-label required" for="loginName">昵称:</label>
                                <input id="loginName" class="form-control" name="loginName" type="text" placeholder="请输入您的昵称"
                                       required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label required" for="holdingPercentage">持仓:</label>
                            <input class="form-control" id="holdingPercentage" name="holdingPercentage" type="number"
                                   step="0.01"
                                   placeholder="例如：100"
                                   required min="0" max="100">
                            <small style="color: red;">注：请填写数字，如100代表100%</small>
                        </div>

                        <!-- 行业选择区域，初始隐藏 -->
                        <div id="industryField" class="form-check">
                            <label class="form-check-label">
                                <span class="required">行业:</span>
                                <div id="checkboxGrid" class="checkbox-grid">
                                    <!-- 复选框将由 JavaScript 动态填充 -->
                                </div>
                            </label>
                            <small id="industryError" style="color: red; display: none;">请选择至少一个行业</small>
                        </div>
                        <div class="d-grid mb-3">
                            <!-- 添加提交按钮 -->
                            <button class="btn btn-primary" type="submit">提交</button>
                        </div>
                    </form>
                </div>
                <div id="message" class="col-auto">
                    <span id="submitInline" class="form-text">
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/static/js/bootstrap5.min.js"></script>
<script src="/static/js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
<script>
    $(document).ready(function () {
        const holdingInput = $("#holdingPercentage");
        const industryField = $("#industryField");
        const form = $("#holdingForm");
        const submitInline = $("#submitInline");
        const urlPrefix = "http://127.0.0.1:8088";

        // 初始化函数
        function init() {
            fetchUserInfo();
            setupHoldingInputListener();
            fetchIndustryData();
            setupLogoutButton();
            setupFormSubmit();
        }

        // 获取用户信息函数
        function fetchUserInfo() {
            $.ajax({
                url: urlPrefix + '/user/info',
                method: 'GET',
                success: function (response) {
                    if (response.authenticated) {
                        $('#userInfo .nav-link:first').text('欢迎，' + response.userName);
                        $('#userInfo').show();
                        $('#loginNameField').hide();
                        $('#userHoldingInfo').show();
                    } else {
                        $('#userInfo').hide();
                        $('#loginNameField').show();
                        $('#userHoldingInfo').hide();
                    }
                },
                error: function (error) {
                    console.error('Error fetching user data:', error);
                }
            });
        }
        // 持仓输入监听函数
        function setupHoldingInputListener() {
            if (holdingInput.length) {
                holdingInput.on("input", function () {
                    const holdingValue = parseFloat(holdingInput.val()) || 0;
                    if (holdingValue > 0) {
                        industryField.show();
                    } else {
                        industryField.hide();
                    }
                });
            }
        }

        // 获取行业数据函数
        function fetchIndustryData() {
            $.ajax({
                url: urlPrefix + '/stock/industrySummary/list',
                method: 'GET',
                success: function (data) {
                    const checkboxGrid = $("#checkboxGrid");
                    if (checkboxGrid.length) {
                        data.forEach(industry => {
                            const label = $("<label></label>");
                            const checkbox = $("<input>").attr({
                                id: "industry-" + industry.id,
                                type: "checkbox",
                                name: "industrySummaryIdList",
                                value: industry.id,
                                class: "form-check-input"
                            });
                            label.append(checkbox);
                            label.append(industry.industryName);
                            checkboxGrid.append(label);
                        });
                    }
                },
                error: function (error) {
                    console.error('Error fetching stock data:', error);
                }
            });
        }

        // 退出登录按钮处理函数
        function setupLogoutButton() {
            // 处理退出登录
            const logoutButton = $("#logoutButton");
            if (logoutButton.length) {
                logoutButton.on("click", function () {
                    $.ajax({
                        url: '/logout',
                        method: 'POST',
                        xhrFields: {
                            withCredentials: true // 确保携带 Cookie
                        },
                        success: function () {
                            // 退出登录成功后刷新页面
                            window.location.reload();
                        },
                        error: function () {
                            alert("退出登录失败，请重试。");
                        }
                    });
                });
            }
        }

        // 表单提交处理函数
        function setupFormSubmit() {
            if (form.length) {
                form.on("submit", function (event) {
                    event.preventDefault();
                    const formData = form.serializeArray();
                    const data = {};
                    $.each(formData, function (i, field) {
                        if (data[field.name] !== undefined) {
                            if (!Array.isArray(data[field.name])) {
                                data[field.name] = [data[field.name]];
                            }
                            data[field.name].push(field.value);
                        } else {
                            data[field.name] = field.value;
                        }
                    });
                    if (data.industrySummaryIdList && !Array.isArray(data.industrySummaryIdList)) {
                        data.industrySummaryIdList = [data.industrySummaryIdList];
                    }
                    $.ajax({
                        url: '/stock/submit',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(data),
                        xhrFields: {
                            withCredentials: true
                        },
                        success: function (response) {
                            if (response.code === 0) {
                                submitInline.css("color", "green").text("提交成功！");
                                window.location.reload();
                            } else if (response.code === 1001) {
                                submitInline.css("color", "red").html("提交失败,该用户不存在，<a href='/register' style='color: #007BFF; text-decoration: underline;'>请先注册</a>！");
                            } else {
                                throw new Error(response.msg || "提交失败");
                            }
                        },
                        error: function (error) {
                            const errorMessage = error.responseJSON && error.responseJSON.msg ? error.responseJSON.msg : '未知错误';
                            submitInline.css("color", "red").text("系统异常: " + errorMessage);
                            console.error('Error submitting form:', error);
                        }
                    });
                });
            }
        }

        // 初始化页面
        init();
    });
</script>

</body>
</html>